package net;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import system.L;

public class Dispatcher {
	public Map<String, Object[]> handlers = new HashMap<String, Object[]>();

	public void register(Object instance, String methodName, Class<?>... types) {
		Method method;
		try {
			method = instance.getClass().getMethod(methodName, types);
			handlers.put(methodName, new Object[] { method, instance });
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}

	public boolean dispatch(String name, Object... args)
			throws IllegalArgumentException, IllegalAccessException,
			InvocationTargetException {
		Object[] pair = handlers.get(name);
		if (pair == null) {
			L.error("no rpc handler: " + name );
			return false;
		} else {
			Method m = (Method) pair[0];
			m.invoke(pair[1], args);
			return true;
		}
	}
}
